//
//  LiveImageUploadController.m
//  BSProject
//
//  Created by nsm on 2020/3/2.
//  Copyright © 2020 beisheng. All rights reserved.
//

#import "LiveImageUploadController.h"
#import "NSMPhotosView.h"

@interface LiveImageUploadController ()
@property (nonatomic, strong) MyLinearLayout *layout;
@property (nonatomic, strong) NSMPhotosView *cards;
@property (nonatomic, strong) UILabel *urlLabel;
@property (nonatomic, strong) UILabel *paramsLabel;
@property (nonatomic, strong) UILabel *fileLabel;
@property (nonatomic, strong) NSArray<NSString *> *urls;
@property (nonatomic, strong) NSArray<NSDictionary *> *params;
@property (nonatomic) int idx;
@property (nonatomic) int fileIdx;
@end

@implementation LiveImageUploadController

#pragma mark - lifeCycle
- (void)didInitialize {
    [super didInitialize];
    
    self.title = @"直播图片上传";
    [self initData:NO];
}

- (void)initData:(BOOL)isOn {
    if (isOn) {
        self.urls = @[@"http://zhiboshow.yanshi.hbbeisheng.com/api/public?service=User.updateAvatar",
                      @"http://zhiboshow.yanshi.hbbeisheng.com/api/public?service=User.updateAvatar&uid=11497&token=2132e71626ee7515e2e2af5fe0d562cc"];
        self.params = @[@{@"uid": @"11497",
                          @"token": @"2132e71626ee7515e2e2af5fe0d562cc"},
                        @{}];
        
        BOOL testUIDINURL = NO;
        if (testUIDINURL) {
        self.urls = @[@"http://zhiboshow.yanshi.hbbeisheng.com/api/public?service=User.updateAvatar&uid=11497",
                      @"http://zhiboshow.yanshi.hbbeisheng.com/api/public?service=User.updateAvatar&uid=11497&token=2132e71626ee7515e2e2af5fe0d562cc"];
        self.params = @[@{@"token": @"2132e71626ee7515e2e2af5fe0d562cc"},
                        @{}];
        }
    } else {
        self.urls = @[@"http://zhiboshow.yanshi.hbbeisheng.com/api/public",
                      @"http://zhiboshow.yanshi.hbbeisheng.com/api/public?service=User.updateAvatar&uid=11497&token=2132e71626ee7515e2e2af5fe0d562cc"];
        self.params = @[@{@"service": @"User.updateAvatar",
                          @"uid": @"11497",
                          @"token": @"2132e71626ee7515e2e2af5fe0d562cc"},
                        @{}];
    }
}

#pragma mark - override

#pragma mark - initialization
- (void)viewDidLoad {
    [super viewDidLoad];
    
    _layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    _layout.backgroundColor = COLOR_4;
    _layout.myHorzMargin = 0;
    _layout.padding = UIEdgeInsetsMake(20, 20, 20, 20);
    _layout.subviewVSpace = 20;
    [self.view addSubview:_layout];
    
    {
        NSMPhotosView *pv = NSMPhotosView.new;
        pv.backgroundColor = GROUP_TABLECOLOR;
        pv.arrangedCount = 4;
        pv.maximumNumberOfPhotos = 9;
        pv.editEnabled = YES;
        pv.deleteEnabled = YES;
        [_layout addSubview:pv];
        _cards = pv;
    }
    
    {
        MyFlowLayout *flow = [MyFlowLayout flowLayoutWithOrientation:MyOrientation_Vert arrangedCount:4];
        flow.myHorzMargin = 0;
        flow.wrapContentHeight = YES;
        flow.subviewHSpace = 6;
        flow.subviewVSpace = 2;
        flow.arrangedGravity = MyGravity_Vert_Center;
        [_layout addSubview:flow];
        
        NSArray *titles = @[@"方式1",@"方式2"];
        __block NSMButton *lastBtn;
        @nsm_weak(self)
        for (int i=0; i<titles.count; i++) {
            NSMButton *btn = NSMButton.new;
            btn.weight = 1;
            btn.height = 44;
            btn.title = titles[i];
            btn.tintColor = COLOR_0;
            [flow addSubview:btn];
            
            [btn setTitleColor:COLOR_0 forState:UIControlStateNormal];
            [btn setTitleColor:COLOR_4 forState:UIControlStateSelected];
            [btn setBackgroundImage:[UIImage imageWithColor:COLOR_3] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageWithColor:UIColor.blueColor] forState:UIControlStateSelected];
            
            if (i==0) {
                btn.selected = YES;
                lastBtn = btn;
            }
            
            [btn addBlockForControlEvents:UIControlEventTouchUpInside block:^(NSMButton *sender) {
                @nsm_strong(self)
                if (sender.selected) {
                    return;
                }
                lastBtn.selected = NO;
                sender.selected = YES;
                lastBtn = sender;
                [self changeLabel:i];
            }];
        }
    }
    
    {
        MyFlowLayout *flow = [MyFlowLayout flowLayoutWithOrientation:MyOrientation_Vert arrangedCount:4];
        flow.myHorzMargin = 0;
        flow.wrapContentHeight = YES;
        flow.subviewHSpace = 6;
        flow.subviewVSpace = 2;
        flow.arrangedGravity = MyGravity_Vert_Center;
        [_layout addSubview:flow];
        
        NSArray *titles = @[@"file",@"file[]"];
        __block NSMButton *lastBtn;
        @nsm_weak(self)
        for (int i=0; i<titles.count; i++) {
            NSMButton *btn = NSMButton.new;
            btn.weight = 1;
            btn.height = 44;
            btn.title = titles[i];
            btn.tintColor = COLOR_0;
            [flow addSubview:btn];
            
            [btn setTitleColor:COLOR_0 forState:UIControlStateNormal];
            [btn setTitleColor:COLOR_4 forState:UIControlStateSelected];
            [btn setBackgroundImage:[UIImage imageWithColor:COLOR_3] forState:UIControlStateNormal];
            [btn setBackgroundImage:[UIImage imageWithColor:UIColor.blueColor] forState:UIControlStateSelected];
            
            if (i==0) {
                btn.selected = YES;
                lastBtn = btn;
            }
            
            [btn addBlockForControlEvents:UIControlEventTouchUpInside block:^(NSMButton *sender) {
                @nsm_strong(self)
                if (sender.selected) {
                    return;
                }
                lastBtn.selected = NO;
                sender.selected = YES;
                lastBtn = sender;
                [self changeFileLabel:i];
            }];
        }
    }
    
    for (int i=0; i<3; i++) {
        UILabel *label = UILabel.new;
        label.backgroundColor = GROUP_TABLECOLOR;
        label.myHorzMargin = 0;
        label.wrapContentHeight = YES;
        label.font = CustomFont(14);
        label.textColor = COLOR_0;
        [_layout addSubview:label];
        
        if (i==0) _urlLabel = label;
        else if (i==1) _paramsLabel = label;
        else if (i==2) _fileLabel = label;
    }
    
    [self changeLabel:0];
    [self changeFileLabel:0];
    
    {
        MyLinearLayout *bottom = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
        bottom.myHorzMargin = 0;
        bottom.wrapContentWidth = NO;
        bottom.wrapContentHeight = YES;
        [_layout addSubview:bottom];
        
        UISwitch *swt = UISwitch.new;
        [swt addTarget:self action:@selector(onChange:) forControlEvents:UIControlEventValueChanged];
        [bottom addSubview:swt];
        
        NSMButton *doneBtn = NSMButton.new;
        doneBtn.size = CGSizeMake(100, 44);
        doneBtn.backgroundColor = UIColor.redColor;
        doneBtn.title = @"提交";
        doneBtn.myAlignment = MyGravity_Horz_Center;
        [doneBtn addTarget:self action:@selector(upload) forControlEvents:UIControlEventTouchUpInside];
        [bottom addSubview:doneBtn];
        
        [bottom equalizeSubviewsSpace:YES];
    }
    
    {
        NSKeyValueObservingOptions options = NSKeyValueObservingOptionInitial | NSKeyValueObservingOptionNew;
        @nsm_weak(self)
        [self.KVOController observe:self.cards keyPaths:@[@"photoViews"] options:options block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSString *,id> * _Nonnull change) {
            @nsm_strong(self)
            [self changeFileLabel:self.fileIdx];
        }];
    }
}

- (void)changeLabel:(int)idx {
    _idx = idx;
    
    _urlLabel.text = FormatString(@"URL:\n%@",_urls[idx]);
    _paramsLabel.text = FormatString(@"参数:\n%@",_params[idx].printString);
}

- (void)changeFileLabel:(int)idx {
    _fileIdx = idx;
    
    NSMutableArray *arr = @[].mutableCopy;
    NSMutableArray *files = @[].mutableCopy;
    NSUInteger cnt = self.cards.photoViews.count;
    if (idx!=0 && cnt>0) {
        [files addObject:@"file[]"];
    }
    for (int i=0; i<cnt; i++) {
        if (idx==0) {
            [files addObject:FormatString(@"file_%d",i)];
        }
        [arr addObject:FormatString(@"%d.jpg",i)];
    }
    _fileLabel.text = FormatString(@"文件字段:\n%@\n文件名:\n%@", [files componentsJoinedByString:@","], [arr componentsJoinedByString:@","]);
}

#pragma mark - setter/getter

#pragma mark - network

#pragma mark - method/public

#pragma mark - method/private
- (void)onChange:(UISwitch *)swt {
    [self initData:swt.isOn];
    [self changeLabel:_idx];
    [self changeFileLabel:_fileIdx];
}

#pragma mark - action
- (void)upload1 {
    NSString *url = @"http://zhiboshow.yanshi.hbbeisheng.com/api/public?service=User.updateAvatar&uid=11497&token=2132e71626ee7515e2e2af5fe0d562cc";
    //    url = @"http://zhiboshow.yanshi.hbbeisheng.com/api/public?service=User.updateAvatar";
    NSDictionary *param = @{@"uid": @"11497",
                            @"token": @"2132e71626ee7515e2e2af5fe0d562cc"};
    //    param = nil;
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session POST:url parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *desc = [(NSDictionary *)responseObject printString];
        NSLog(@"%@",desc);
        [self showAlert:desc action:nil];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString *desc = error.description;
        NSLog(@"%@",desc);
        [self showAlert:desc action:nil];
    }];
}
- (void)upload {
    [MBProgressHUD showHUDAddedTo:_keyWindow animated:YES];
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    @nsm_weak(self)
    NSLog(@"url:%@\n参数:%@", _urls[_idx], _params[_idx]);
    [session POST:_urls[_idx] parameters:_params[_idx] constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        @nsm_strong(self)
        for (int i=0; i<self.cards.photoViews.count; i++) {
            NSMPhotoImageView *imageView = self.cards.photoViews[i];
            if (imageView.image) {
                NSString *name = @"file[]";
                if (self.fileIdx==0) {
                    name = FormatString(@"file_%d",i);
                    name = @"file";
                }
                [formData appendPartWithFileData:UIImageJPEGRepresentation(imageView.image, 0.7)
                                            name:name
                                        fileName:FormatString(@"%d.jpg",i+1)
                                        mimeType:@"image/jpeg"];
            }
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:_keyWindow animated:NO];
        @nsm_strong(self)
        [self showAlert:[(NSDictionary *)responseObject printString] action:nil];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:_keyWindow animated:NO];
        [self showAlert:error.description action:nil];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
